package com.hjn.springboot.springbootinterceptor.config;

import com.hjn.springboot.springbootinterceptor.entity.po.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author huaijn
 * @date 2022/4/29 /0029-16:45
 * @description todo
 */
public class UserInteceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截的规则
        //从session中获取用户的信息
        User user = (User) request.getSession().getAttribute("user");
        System.out.println("进入拦截器.........."+ LocalDateTime.now());
        //判断用户是否为空
        if (null == user) {
            response.sendRedirect(request.getContextPath() + "/user/nologin");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
